import { RejectFn, ResolveFn } from "../types";

interface interceptor<T> {
  resolved: ResolveFn<T>;
  rejected?: RejectFn;
}

export default class InterceptorManage<T> {
  // 拦截器管理器
  private interceptors: Array<interceptor<T> | null>;
  constructor() {
    this.interceptors = [];
  }

  // 把拦截器加进入
  use(resolved: ResolveFn<T>, rejected?: RejectFn): number {
    this.interceptors.push({
      resolved,
      rejected,
    });
    return this.interceptors.length - 1;
  }

  // 删除拦截器
  eject(id: number): void {
    if (this.interceptors[id]) {
      this.interceptors[id] = null;
    }
  }

  forEach(fn: (interceptor: interceptor<T>) => void): void {
    this.interceptors.forEach((interceptor) => {
      if (interceptor !== null) {
        fn(interceptor);
      }
    });
  }
}
